import React, {useEffect, useState} from 'react'
import {Form, DatePicker, Input, Row, Col, Select, Cascader, Table} from 'antd'
import moment from 'moment'
import {getContractSubjectList, getRelativeRecordsInfo, getContractModelList, getEmployeeById} from "../service";
import {
  laborContractYearsList,
  genderList,
  probationDayList,
  contractTypeStatusList,
  newContractStatusList,
  FamilyRelationList
} from "@/utils/constant";
import {resultDate, resultMonthDay} from "@/utils/utils";

const FormItem = Form.Item;
const {RangePicker} = DatePicker;
const {Option} = Select;

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

const CreateForm = (props) => {
  const {record, form, loading, nativePlace, statusType, jobType} = props;
  const [contractData, setContractData] = useState([]);
  const [type, setType] = useState(null);
  const [dataValue, setDataValue] = useState(0);
  const [serverText, setServerText] = useState(null);
  const [data, setData] = useState([{}]);
  const [flag, setFlag] = useState(null);
  const [contractList, setContractList] = useState([]);
  const [tempContractType, setTempContractType] = useState(0);
  const [relativesData, setRelativesData] = useState([]);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [clickedCancel, setClickedCancel] = useState(false);
  const [disabledList, setDisabledList] = useState([]);
  const [dateList, setDateList] = useState([]);


  useEffect(() => {
    if (record) {
      setDateList(resultMonthDay());
      getEmployeeById(record.oid).then(res => {
        let age = (moment().format('YYYY') - moment(res.birthday).format('YYYY'));
        let endOfTrialPeriod = moment(res.hiredate).add(res.probationday, 'month');
        const value = parseInt(res.laborContractYears);
        let timeType = value === 0 ? 'month' : 'years';
        setType(timeType);
        if (value === 0) {
          setDataValue(6);
        } else {
          setDataValue(value);
        }
        let temp = resultDate(record.newContractBeginDate ? record.newContractBeginDate : record.contractBeginDate, value, timeType);
        if (temp[1]) {
          setDisabledList([true, true]);
        } else {
          setDisabledList([false, false]);
        }
        form.setFieldsValue({
          ...res,
          age: age,
          hiredate: res.hiredate ? moment(res.hiredate) : undefined,
          endOfTrialPeriod: endOfTrialPeriod || undefined,
          workAddress: '',
          contractStatus: statusType === 'newSign' ? 1 : 2,
          contractType: 1,
          contractPeriodType: '固定期限合同',
          contractTempDate: temp,
          oldCompanyName: res.employerCompany
        });
      });
      getContractModelList(record.contractType, record.type).then(res => {
        setContractList(res);
      });
      //获取合同主体
      getContractSubjectList().then(res => {
        setContractData(res)
      })
    }
    setTempContractType(0);
    setFlag(false);
    setData([{}]);
  }, [record]);

  const setNativePlaceLabel = (label) => {
    if (typeof label !== 'string') {
      return label.join('');
    } else {
      return [label].join('');
    }
  };

  const getAddress = (value, selectedOptions, type) => {
    let temp;
    if (selectedOptions.length === 0) {
      return
    }
    if (selectedOptions.length > 1) {
      temp = selectedOptions[0].title + selectedOptions[1].title
    } else {
      temp = selectedOptions[0].title
    }
    if (type === 'contract') {
      form.setFieldsValue({contract: temp});
    } else {
      form.setFieldsValue({work: temp});
    }
  };

  const relativeRecordsColumns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    },
    {
      title: '身份证号码',
      dataIndex: 'idcard',
      key: 'idcard',
      align: 'center'
    },
    {
      title: '任职单位/部门',
      dataIndex: 'unit',
      key: 'unit',
      align: 'center'
    },
    {
      title: '任职岗位',
      dataIndex: 'job',
      key: 'job',
      align: 'center'
    },
    {
      title: '关系类别',
      dataIndex: 'isDirectRelative',
      key: 'isDirectRelative',
      render: (text, record) => {
        const res = FamilyRelationList.find((item) => item.value === parseInt(text))
        return res ? res.label : text
      },
      align: 'center'
    },
    {
      title: '与本人关系',
      dataIndex: 'relative',
      key: 'relative',
      align: 'center'
    }
  ]

  const proxyColumns = [
    {
      title: '服务公司主体',
      dataIndex: 'serverId',
      key: 'serverId',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择服务公司主体" className='widthStyle' value={data.length > 0 ? data[0].serverId : ''}
                    onChange={(e) => handleFieldChange(e, 'serverId', record.key)} showSearch
                    filterOption={(input, option) =>
                      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
              {contractData.length > 0 ? contractData.map((item, index) => {
                return (
                  <Option value={item.id} key={index}>
                    {item.name}
                  </Option>
                )
              }) : ''}
            </Select>
          )
        }
        return text ? contractData.find(item => item.id === text)?.name : '';
      },
    },
    {
      title: '服务工作单位',
      dataIndex: 'serverName',
      key: 'serverName',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input
              value={text}
              autoFocus
              onChange={(e) => handleFieldChange(e, 'serverName', record.key)}
              placeholder="服务工作单位"
            />
          )
        }
        return text
      },
    },
    {
      title: '操作',
      key: 'action',
      width: '160px',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
                <a onClick={(e) => saveRow(e, record.key)}>保存</a>
              </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
          </span>
        )
      },
    },
  ]

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0];

  const toggleEditable = (e, key) => {
    e.preventDefault();
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData);
      }
      target.editable = !target.editable;
      setData(newData);
      form.setFieldsValue({data: newData});
    }
  };

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      setData(newData)
    }
    ;
  };

  const saveRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return;
    }
    toggleEditable(e, rowKey);
  };

  const handleSelectChange = (value, text) => {
    setServerText(text.key)
  };

  const [dates, setDates] = useState([]);
  const disabledDate = current => {
    if (!dates || dates.length === 0) {
      return false;
    }
    const tooLate = dates[0] && current.diff(dates[0], type) >= dataValue;
    const tooEarly = dates[1] && dates[1].diff(current, type) >= dataValue;
    return tooEarly || tooLate;
  };

  const getEnterpriseNatureInfo = (value, option) => {
    form.setFieldsValue({
      enterpriseNature: option.lable.property,
      legalPerson: option.lable.representative,
      registeredAddress: option.lable.registeredAddress
    })
  };

  const handleTemplate = (value, item) => {
    if (statusType !== 'newSign') {
      if (item.children.indexOf('-固定期限续签') > -1) {
        form.setFieldsValue({contractPeriodType: '固定期限合同'});
      } else {
        form.setFieldsValue({contractPeriodType: '不固定期限合同'});
      }
    }
    setTempContractType(item.lable.detailType);
    if (['2', '4', '6','32'].indexOf(item.lable.detailType) > -1) {
      setFlag(true);
      getRelativeRecordsInfo(record.oid).then(res => {
        setRelativesData(res);
      })
    } else {
      setRelativesData([]);
      setFlag(false);
    }
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="合同人姓名">
              <Input placeholder="请输入" disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="gender" label="性别">
              <Select placeholder="请选择" disabled={true}>
                {genderList.map((item, index) => {
                  return (
                    <Option value={`${item.value}`} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="age" label="年龄">
              <Input placeholder="请输入" disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitname" label="部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="hiredate" label="入职日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="mobile" label="联系方式">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="idcard" label="身份证">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="probationday" label="试用期" rules={[{required: true, message: '试用期不能为空'}]}>
              <Select disabled={true} placeholder="请选择">
                {probationDayList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="address" label="家庭住址" rules={[{required: true, message: '家庭住址不能为空'}]}>
              <Input disabled={true} placeholder="家庭住址详细到门牌号"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="regresidence" label="户口所在地" rules={[{required: true, message: '户口所在地不能为空'}]}>
              <Input disabled={true} placeholder="请输入户口所在地"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="laborContractYears" label="合同期限" rules={[{required: true, message: '合同期限不能为空'}]}>
              <Select placeholder="请选择合同期限" disabled={true}>
                {laborContractYearsList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="contractTempDate" label="合同起止日期" rules={[{required: true, message: '合同起止日期不能为空'}]}>
              <RangePicker disabled={disabledList} className='widthStyle' onCalendarChange={value => {
                setDates(value);
              }}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="endOfTrialPeriod" label="试用期结束日期">
              <DatePicker disabled={true} placeholder="请选择日期" style={{width: '100%'}}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="contractAddress" label="签订地点" rules={[{required: true, message: '签约地点不能为空'}]}>
              <Cascader fieldNames={{label: 'title', value: 'value', children: 'children'}}
                        onChange={(value, selectedOptions) => getAddress(value, selectedOptions, 'contract')}
                        displayRender={(label) => setNativePlaceLabel(label)} placeholder="请输入" options={nativePlace}/>
            </FormItem>
          </Col>
          <Col span={0}>
            <FormItem name="contract">
              <Input/>
            </FormItem>
          </Col>
          <Col span={statusType === 'newSign' ? 0 : 8}>
            <FormItem name="oldCompanyName" label="过期甲方主体">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="contractPeriodType" label="合同期限类型">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="server" label="从事工作类型" rules={[{required: true, message: '工作类型不能为空'}]} extra={serverText}>
              <Select placeholder="请选择工作类型" onChange={handleSelectChange} showSearch allowClear>
                {jobType && jobType.map((item, index) => {
                  return (
                    <Option value={item.name} key={item.value}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="companyId" label="甲方主体" rules={[{required: true, message: '甲方主体不能为空'}]}>
              <Select placeholder="请选择甲方主体" onChange={getEnterpriseNatureInfo} showSearch
                      filterOption={(input, option) =>
                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
                {contractData.length > 0 ? contractData.map((item, index) => {
                  return (
                    <Option value={item.id} key={index} lable={item}>
                      {item.name}
                    </Option>
                  )
                }) : ''}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="enterpriseNature" label="企业性质">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="legalPerson" label="法人代表">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="registeredAddress" label="注册地址">
              <Input disabled={true}/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="workAddress" label="合同工作地" rules={[{required: true, message: '合同工作地不能为空'}]}>
              <Cascader fieldNames={{label: 'title', value: 'value', children: 'children'}} changeOnSelect
                        onChange={(value, selectedOptions) => getAddress(value, selectedOptions, 'work')}
                        displayRender={(label) => setNativePlaceLabel(label)} placeholder="请输入" options={nativePlace}/>
            </FormItem>
          </Col>
          <Col span={0}>
            <FormItem name="work">
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="salary" label="合同工资标准" rules={[{required: true, message: '合同工资标准不能为空'}]}>
              <Input placeholder="请输入合同月薪" suffix="元"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="salaryDate" label="发薪日期" rules={[{required: true, message: '发薪日期不能为空'}]}>
              <Select placeholder="请选择发薪日期">
                {dateList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.title}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="modelId" label="签订模板" rules={[{required: true, message: '签订模板不能为空'}]}>
              <Select placeholder="请选择签订模板" onChange={handleTemplate}>
                {contractList.map((item, index) => {
                  return (
                    <Option value={item.id} key={index} lable={item}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="contractType" label="合同类型">
              <Select disabled={true} placeholder="请选择合同类型">
                {contractTypeStatusList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="contractStatus" label="合同状态">
              <Select disabled={true} placeholder="请选择合同状态">
                {newContractStatusList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col span={0}>
            <FormItem name="data">
              <Input/>
            </FormItem>
          </Col>
          {
            flag && <Col span={24}>
              <Table
                style={{marginBottom: 24}}
                title={() => '亲属关系信息'}
                rowKey="id"
                size="small"
                bordered
                pagination={false}
                loading={loading}
                dataSource={relativesData}
                columns={relativeRecordsColumns}
              />
            </Col>
          }
          {
            (['5', '6', '15', '16', '22', '23', '31', '32', '33', '34', '35', '36'].indexOf(tempContractType) > -1) &&
            <Col span={24}>
              <Table
                title={() => '服务公司信息'}
                rowKey="1"
                size="small"
                bordered
                style={{marginBottom: 24}}
                pagination={false}
                loading={loading}
                dataSource={data}
                columns={proxyColumns}
              />
            </Col>
          }
        </Row>
      </>
    )
  };

  return (renderContent())
};


export default CreateForm;
